package com.wuji1626.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Administrator
 * @version 1.0
 * @description: 以流的形式处无界数据
 * @date 2025/3/8 16:52
 */
public class Flink03_Unbound_Stream {

    public static void main(String[] args) {
        // step1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // step2 从指定的网络端口读取数据
        DataStreamSource<String> socksetDS = env.socketTextStream("localhost", 8888);
        // step3 对读取的数据进行扁平化处理，封装为二元组对象向下游传递 Tuple2<String, Long>
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMapDS = socksetDS.flatMap(
                new FlatMapFunction<String, Tuple2<String, Long>>() {

                    @Override
                    public void flatMap(String lineStr, Collector<Tuple2<String, Long>> out) throws Exception {
                        for (String word : lineStr.split(" ")) {
                            out.collect(Tuple2.of(word, 1L));
                        }
                    }
                }
        );
        // step4 按照单词进行分组
        KeyedStream<Tuple2<String, Long>, Tuple> keyedDS = flatMapDS.keyBy(0);
        // step5 求和计算
        SingleOutputStreamOperator<Tuple2<String, Long>> sumDS = keyedDS.sum(1);
        // step6 将结果打印输出
        sumDS.print();
        // step7 提交作业
        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
